package com.castle.fortress.admin.job.task;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.castle.fortress.admin.oa.entity.DateHolidayEntity;
import com.castle.fortress.admin.oa.service.DateHolidayService;
import com.castle.fortress.admin.utils.OpenApiUtil;
import com.castle.fortress.admin.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;


/**
 * 获取法定节假日
 */
@Component("checkToDayIsHolidays")
public class CheckToDayIsHolidaysTask implements ITask {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    DateHolidayService dateHolidayService;

    @Autowired
    OpenApiUtil openApiUtil;

    @Override
    public void runTask(String params) {
        System.out.println("调用节假日任务");
        try {
            dateHolidayService.remove(null);
            int field = DateTime.now().getField(DateField.YEAR);
            final Map<String, String> queryParams = new HashMap<>();
            queryParams.put("year", field + "");
            final String response = openApiUtil.doGet("/life/holidayList", queryParams);
            System.out.println("response");
            System.out.println(response);
            final JSONObject jsonResponse = JSONUtil.parseObj(response);
            final JSONObject data = JSONUtil.parseObj(jsonResponse.getStr("data"));
            final JSONObject apiResBody = JSONUtil.parseObj(data.getStr("showapi_res_body"));
            final JSONArray holidayList = JSONUtil.parseArray(apiResBody.get("data"));
            for (Object object : holidayList) {
                JSONObject entries = JSONUtil.parseObj(object);
                int begin = entries.getInt("begin");
                int end = entries.getInt("end");
                createHoliday(begin, end);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createHoliday(int begin, int end) {
        DateTime beginDate = DateTime.of(begin + "", DatePattern.PURE_DATE_PATTERN);
        DateTime endDate = DateTime.of(end + "", DatePattern.PURE_DATE_PATTERN);
        DateTime now = beginDate;
        do {
            DateHolidayEntity temp = new DateHolidayEntity();
            temp.setDate(beginDate.toDateStr());
            temp.setType(3);
            dateHolidayService.save(temp);
            now.offset(DateField.DAY_OF_YEAR, 1);
        } while (now.getTime() <= endDate.getTime());
    }
}
